package com.xbb.dao

import java.util

import com.xbb.analysis.CourseSearchCount
import com.xbb.utils.HBaseUtil
import org.apache.hadoop.hbase.client._
import org.apache.hadoop.hbase.util.Bytes

import scala.collection.mutable.ListBuffer

object CourseSearchCountDAO {
  val tableName = "imooc:course_search"
  val columnFamily = "info"
  val qualifier = "click_count"

  def saveList(list: ListBuffer[CourseSearchCount]): Unit = {
    val table: Table = HBaseUtil.getInstance().getTable(tableName)
    for (elem <- list) {
      table.incrementColumnValue(
        elem.rowKey.getBytes(),
        columnFamily.getBytes(),
        qualifier.getBytes(),
        elem.click_count
      )
    }
  }

  def scanByKey(rowKey: String): Long = {
    val table: Table = HBaseUtil.getInstance().getTable(tableName)
    val get = new Get(rowKey.getBytes())
    val value: Array[Byte] = table.get(get).getValue(columnFamily.getBytes(), qualifier.getBytes())

    if (value == null) {
      0L
    } else Bytes.toLong(value)
  }

  def scan(): Unit = {
    val table: Table = HBaseUtil.getInstance().getTable(tableName)

    val scan = new Scan()
    scan.addColumn(columnFamily.getBytes(), qualifier.getBytes())
    val resultScanner: ResultScanner = table.getScanner(scan)

    val result: util.Iterator[Result] = resultScanner.iterator()
    while (result.hasNext) {
      val res: Result = result.next()
      print(Bytes.toString(res.getRow) + "\t")
      println(Bytes.toLong(res.getValue(columnFamily.getBytes(), qualifier.getBytes())))
    }
  }

  def main(args: Array[String]): Unit = {
    scan()
  }
}
